import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeAll, setUsername, setSuper, getUsername, getSuper } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: getUsername(),
    is_super: getSuper()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_SUPER: (state, is_super) => {
    state.is_super = is_super
  },
  SET_NAME: (state, name) => {
    state.name = name
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        console.log(data)
        commit('SET_TOKEN', data.token)
        commit('SET_NAME', data.username)
        commit('SET_SUPER', data.is_super)
        setToken(data.token)
        setUsername(data.username)
        setSuper(data.is_super)
        resolve()
      }).catch(error => {
        reject(error)
        console.log(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { name, avatar } = data
        commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve) => {
      removeAll() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeAll() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  changeToken({ commit }, restToken) {
    console.log('1111111' + restToken)
    return new Promise(resolve => {
      commit('SET_TOKEN', restToken)
      setToken(restToken)
      resolve()
    })
  }
}

export default {
  namespaced: true, // 局部命名空间
  state,
  mutations,
  actions
}

